﻿# 该文件为其上传文件相关的函数
from distutils.filelist import FileList
import os
import ftplib

def connect_ftp(hostname, username, password):
    ftp = ftplib.FTP(hostname)
    ftp.login(username, password)
    return ftp

# 上传文件的方法
def upload_file(ftp, local_file_path, remote_file_path):
    with open(local_file_path, 'rb') as f:
        ftp.storbinary('STOR ' + remote_file_path, f)

# 上传文件夹的方法
def upload_dir(ftp, local_dir_path, remote_dir_path):
    # 打印文件夹中的列表
    print(os.listdir(local_dir_path))
    # 遍历文件夹列表
    for name in os.listdir(local_dir_path):
        local_path = os.path.join(local_dir_path, name)
        remote_path = os.path.join(remote_dir_path, name)
        # 修改路径
        new_remote_path = ""
        for value in remote_path:
            if(value == "\\"):
                new_remote_path += '/'
            else:
                new_remote_path += value
        print('我是待上传的文件',local_path, new_remote_path)
        if os.path.isfile(local_path):
            print('判断是否走该分支',os.path.isfile(local_path))
            print('上传的相关路径',local_path, new_remote_path)
            upload_file(ftp, local_path, new_remote_path)
        elif os.path.isdir(local_path):
            
            print("目录文件名称：", new_remote_path)
            fileList = ftp.nlst()
            flag = 0
            print(os.path.basename(new_remote_path))
            for i in fileList:
                if(i == os.path.basename(new_remote_path)):
                    flag = 1
            if(flag ==  0):
                ftp.mkd(new_remote_path)
            ftp.cwd(new_remote_path)
            # 递归调用
            upload_dir(ftp, local_path, new_remote_path)
        ftp.cwd("..")
    

#定义的ftp关闭函数
def close_ftp(ftp):
    ftp.quit()

#定义的是下载函数
def download_file(ftp, remote_path, local_path):
    # 获取ftp的文件列表
    fileList = ftp.nlst()
    print(fileList)
    for i in fileList:
        print(remote_path + "/" + i)
        # 如果不是文件夹的话
        if(i.find('.') != -1):
            print("本地路径", local_path + "\\" + i)
            with open(local_path + "\\" + i, 'wb') as f:
                ftp.retrbinary('RETR ' + remote_path + "/" + i, f.write)
        else:
            # 创建文件夹
            print("目录名称", i)
            if not os.path.exists(local_path + "\\" + i):
                os.makedirs(local_path + "\\" + i,  mode=0o777)
            ftp.cwd(remote_path + "/" + i)
            download_file(ftp, remote_path + "/" + i, local_path + "\\" + i)
       